package cn.bone.auth.security.base.conf;

import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){

//        SecureRandom secureRandom = null;
//        try {
//            secureRandom = SecureRandom.getInstance("SHA1PRNG");
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        return new BCryptPasswordEncoder(4, secureRandom);

        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("bone").password("123456").roles("admin")
                .and()
                .withUser("abc").password("123456").roles("user");
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/admin").hasRole("admin")
                .antMatchers("/user").hasRole("user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/myLogin")
                .usernameParameter("myUser")
                .passwordParameter("myPass")
                .successHandler((request, response, authentication)->{
                    response.setContentType("application/json;charset=utf-8");
                    JSONObject obj = new JSONObject();
                    obj.put("code", 0);
                    obj.put("message", "登录成功");
                    obj.put("data", "");
                    PrintWriter writer = response.getWriter();
                    writer.write(obj.toJSONString());
                    writer.flush();
                })
                .failureHandler(((request, response, exception) -> {
                    response.setContentType("application/json;charset=utf-8");
                    JSONObject obj = new JSONObject();
                    obj.put("code", 1002);
                    obj.put("message", "登录失败");
                    obj.put("data", "");
                    PrintWriter writer = response.getWriter();
                    writer.write(obj.toJSONString());
                    writer.flush();
                }))
                .and()
                .logout()
                .logoutUrl("/myLogout")
                .logoutSuccessHandler((request, response, authentication) -> {
                    response.setContentType("application/json;charset=utf-8");
                    JSONObject obj = new JSONObject();
                    obj.put("code", 0);
                    obj.put("message", "退出登录成功");
                    obj.put("data", "");
                    PrintWriter writer = response.getWriter();
                    writer.write(obj.toJSONString());
                    writer.flush();
                })
                .and()
                .csrf().disable()
                .exceptionHandling()
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    System.out.println("空实现");
                })
                .authenticationEntryPoint(new CustomEntryPoint());
    }
}
